//
//  UINavigationController+Extension.m
//  s.
//
//  Created by 谈虎啸 on 2022/9/14.
//  Copyright © 2022 J. All rights reserved.
//

#import "UINavigationController+Extension.h"

@implementation UINavigationController (Extension)

- (void)jy_pushViewController:(UIViewController *)viewController
                     popCount:(NSInteger)popCount
                     animated:(BOOL)animated {
    
    [self pushViewController:viewController animated:animated];
    if (self.viewControllers.count > 2) {
        NSMutableArray *mviewControllers = [self.viewControllers mutableCopy];
        for (NSInteger i = 0; i < popCount + 1; i++) {
            if (mviewControllers.count > 1) {
                [mviewControllers removeLastObject];
            }
        }
        [mviewControllers addObject:viewController];
        [self setViewControllers:mviewControllers animated:NO];
    }
}
- (void)jy_popRootAndPushViewController:(UIViewController *)viewController
                                animated:(BOOL)animated {
    [self jy_pushViewController:viewController popCount:self.viewControllers.count - 1 animated:animated];
}

/** pop到指定控制器*/
- (void)jy_popToDesVc:(NSString *)vcName
{
    if (!vcName) {
        return;
    }
    Class type = NSClassFromString(vcName);
    UIViewController *desVc = nil;
    for (UIViewController *vc in self.viewControllers) {
        if ([vc isKindOfClass:type]) {
            desVc = vc;
            break;
        }
    }
    if (desVc) {
        [self popToViewController:desVc animated:YES];
    }else {
        NSLog(@"no search des vc - %@", vcName);
    }
}
/** pop掉cnt个控制器*/
- (void)jy_popToCnt:(NSInteger)cnt
{
    if (cnt < 0) {
        return;
    }
    if (self.viewControllers.count <= cnt) {
        return;
    }
    NSInteger totalCnt = self.viewControllers.count;
    for (int i = 0; i < totalCnt; i ++) {
        UIViewController *vc = self.viewControllers[i];
        if (i == totalCnt - cnt - 1) {
            
            [self popToViewController:vc animated:YES];
            break;
        }
    }
}

@end
